<?php

namespace forfun\annotation;

use forfun\constant\ErrorCode;
use forfun\context\CoreContext;
use forfun\service\UserService;
use restphp\aop\AopParam;
use restphp\http\RestHttpRequest;
use restphp\utils\RestStringUtils;
use Sofical\Restphp\exception\BaException;

/**
 * @Aspect (name="Logon")
 */
class Logon {
    private static $_headerKey = 'F-Token';
    private static $_userToken = '';

    /**
     * @param AopParam $aopParam
     * @return void
     * @throws BaException
     */
    function before($aopParam)
    {
        self::$_userToken = RestHttpRequest::getHttpHeader(self::$_headerKey);
        if (RestStringUtils::isBlank(self::$_userToken)) {
            throw new BaException(ErrorCode::USER_AUTH_ACCESS_DEFINED);
        }

        $user = UserService::getUserByToken(self::$_userToken);
        if (null == $user) {
            throw new BaException(ErrorCode::USER_AUTH_ACCESS_DEFINED);
        }
        CoreContext::setUser($user);
    }
}